﻿(function () {
    $.extend($.fn, {
        AutoComboBox: function (op) {
            if ($.type(op) === "string")  //这里要写3个=  
            {
                if (op == "GetVal")
                    return;
            }
            op = $.extend({
                url: false,                         //获取数据的地址   
                item: {},                           //分类深度
                initialValue: 0,                    //第一次请求id初始值
                type: "GET",                        //请求远程数据的方式 get/post
                idPrefix: "",                       //自动生成下拉框的 默认ID前缀[暂不支持]
                thisobject: false,                  //当前对象,不需要赋值
                expandAnimation: false,             //展开时候的动画 默认为show
                shrinkAnimation: false,             //合并时候的动画 默认为hide
                splitchar: '/',                      //值和文本的分隔符 默认为'/'
                complete: function (value, text) { } //当最后一级选择完成时 触发此事件
            }, op);
            op.width = op.width ? op.width : 300; //如果没有用户没有设置宽度 则默认300;
            op.thisobject = this;
            this.CreateLayout(op);
            return this;
        },
        CreateLayout: function (op) {
            var htmlTemplate = '';
            htmlTemplate = htmlTemplate + '<div class="jAutoComboBox-address-inputbox">';
            htmlTemplate = htmlTemplate + '    <span>';
            htmlTemplate = htmlTemplate + '        <input type="text" class="jAutoComboBox-address-input" />';
            htmlTemplate = htmlTemplate + '        <i class="bottom-arrow"></i>';
            htmlTemplate = htmlTemplate + '   </span>';
            htmlTemplate = htmlTemplate + '    <div class="jAutoComboBox-address-content">';
            htmlTemplate = htmlTemplate + '        <ul class="jAutoComboBox-address-list">{items}';
            htmlTemplate = htmlTemplate + '        </ul>';
            htmlTemplate = htmlTemplate + '        {itemscontainer}';
            htmlTemplate = htmlTemplate + '    </div>';
            htmlTemplate = htmlTemplate + '</div>';

            var items = "";
            var itemscontainer = "";
            var inx = 0;     //li计数
            $.each(op.item, function (key) {
                var value = op.item[key];
                items = items + "<li  " + (inx == 0 ? "class='jAutoComboBox-address-first' style=''" : "class='jAutoComboBox-address-other'") + " key='" + key + "'>" + value + "</li>";
                itemscontainer = itemscontainer + " <div class='jAutoComboBox-address-con' key='" + key + "'></div>";
                inx++;
            });
            htmlTemplate = htmlTemplate.replace("{items}", items);
            htmlTemplate = htmlTemplate.replace("{itemscontainer}", itemscontainer);

            $(this).append(htmlTemplate);
            $(this).find('div[class="jAutoComboBox-address-content"]').hide();
            /*处理宽度*/
            var inputwidth = op.width - 5 - 2;//input宽度
            var liwidth = (op.width - (inx + 1)) / inx;
            var firstLiwidth = 0;
            if (parseInt(liwidth) != liwidth)  //是否能够整除,若能整除则li宽度相同,否则设置第一个Li宽度自动适应取整
            {
                //不能整除,
                liwidth = parseInt(liwidth);//把小数强制转换成整数
                firstLiwidth = (op.width - (inx + 1)) - liwidth * (inx - 1);
            }

            $(this).css("width", op.width + "px");//设置容器宽度
            $(this).find('div[class="jAutoComboBox-address-content"]').css("width", (op.width - 2) + "px");//设置子类容器宽度
            $(this).find('div[class="jAutoComboBox-address-con"]').css("width", (op.width - 2 - 40) + "px");
            $(this).find("input").css("width", inputwidth + "px").attr("splitchar", op.splitchar);//设置input宽度
            $(this).find("ul li").css("width", liwidth + "px");//设置li宽度
            if (firstLiwidth) //需要自适应第一个li宽度
            {
                $(this).find("ul li:first").css("width", firstLiwidth + "px");//设置第一个li宽度
            }

            $(this).find("ul li:first").addClass("jAutoComboBox-address-selected");
            /*绑定事件*/
            this.BindEvent.InoutFocusout($(this).find("input"), op);
            this.BindEvent.InputClick($(this).find("input"), op);
            this.BindEvent.LiClick($(this).find("li[key]"), op);

            this.LoadRemoteData(op, $(this).find("ul li:first").attr("key"), op.initialValue);
        },
        BindEvent: {
            InoutFocusout: function (input, op) {
                input.focusout(function () {
                    if (input.val()) {
                        op.thisobject.Methods.GetVal(op.thisobject, false);
                    }
                    else {
                        $(op.thisobject).find('a[itemid][class*="selected"]').removeClass("selected");
                        input.attr("itemid", "");
                    }
                });
            },
            InputClick: function (input, op) {
                input.click(function () {
                    op.thisobject.Show(op.expandAnimation ? op.expandAnimation : "show");
                });
                $(document).click(function (e) {
                    e = e || window.event;
                    var classname = $(e.target).attr("class");
                    if (!classname) {
                        classname = $(e.target).parent().attr("class");
                    }
                    if (classname && classname.length > 0 && classname.indexOf("jAutoComboBox-address-") > -1)
                        return;
                    else {
                        op.thisobject.Show(op.shrinkAnimation ? op.shrinkAnimation : "hide");
                    }
                });
            },
            LiClick: function (lis, op) {
                lis.click(function () {
                    var keyname = $(this).attr("key");
                    if ($(op.thisobject).find('li[class*="jAutoComboBox-address-selected"]') == $(this)) {
                        return;
                    }

                    var selectedkeyname = $(op.thisobject).find('li[class*="jAutoComboBox-address-selected"]').attr("key");
                    //取消以前选定的并且隐藏
                    $(op.thisobject).find('li[key="' + selectedkeyname + '"]').removeClass("jAutoComboBox-address-selected");
                    $(op.thisobject).find('div[class="jAutoComboBox-address-con"][key="' + selectedkeyname + '"]').hide();


                    //设置现在的选定状态
                    $(op.thisobject).find('li[key="' + keyname + '"]').addClass("jAutoComboBox-address-selected");
                    $(op.thisobject).find('div[class="jAutoComboBox-address-con"][key="' + keyname + '"]').show();
                });
            },
            AClick: function (As, op) {
                As.click(function () {
                    var itemid = $(this).attr("itemid");
                    var text = $(this).text();
                    var nowcon = $(this).parent('div');
                    var nextcon = $(this).parent('div').next('div');
                    if (nextcon.length > 0) {
                        var nowkeyname = nowcon.attr("key");
                        var nextkeyname = nextcon.attr("key");

                        /*清空下一步的项便于下一行代码执行重新加载以及重新获取选定的项*/
                        nowcon.nextAll('div[class="jAutoComboBox-address-con"]').html("");

                        /*为下一步加载数据*/
                        op.thisobject.LoadRemoteData(op, nextkeyname, itemid);

                        //取消当前选定并且隐藏
                        $(op.thisobject).find('li[key="' + nowkeyname + '"]').removeClass("jAutoComboBox-address-selected");
                        $(op.thisobject).find('div[class="jAutoComboBox-address-con"][key="' + nowkeyname + '"]').hide();

                        //设置下一步为选定
                        $(op.thisobject).find('li[key="' + nextkeyname + '"]').addClass("jAutoComboBox-address-selected");
                    }
                    else {
                        //已经是最后一级
                        op.thisobject.Show(op.shrinkAnimation ? op.shrinkAnimation : "hide");

                    }

                    //设置当前分类的样式
                    $(this).parent('div').find('a').removeClass("selected");
                    $(this).addClass("selected");
                    //设置选定项的文字

                    var input = $(op.thisobject).find("input[class='jAutoComboBox-address-input']");
                    input.val("");
                    var value = ""; //ID值
                    $(op.thisobject).find('a[itemid][class*="selected"]').each(function (i, item) {
                        if (input.val()) {
                            input.val(input.val() + op.splitchar + $(item).text());
                            input.attr("itemid", input.attr("itemid") + op.splitchar + $(item).attr("itemid"))
                        }
                        else {
                            input.val($(item).text());
                            input.attr("itemid", $(item).attr("itemid"));
                        }
                    });

                    if (nextcon.length == 0) {
                        if (op.complete) {
                            op.complete(input.val(), input.attr("itemid"));
                        }
                    }
                });
            }
        },
        LoadRemoteData: function (op, keyname, itemid) {
            if (op.url) {    //从远程获取数据
                $.ajax({
                    type: op.type,
                    url: op.url,
                    data: "ID=" + itemid,
                    success: function (msg) {
                        op.data = eval(msg);
                        op.thisobject.CreateItemData(op, keyname);
                    }, error: function () {
                    }
                });
            }
        },
        CreateItemData: function (op, keyname) {

            var htmlTemplate = "";
            $.each(op.data, function (i, item) {
                htmlTemplate = htmlTemplate + "<a href='javascript:;' key='" + keyname + "' class='jAutoComboBox-address-autocomboboxitem' itemid='" + item.id + "'>" + item.text + "</a>";
            });
            $(this).find('div[class="jAutoComboBox-address-con"][key="' + keyname + '"]').html(htmlTemplate).show();
            op.thisobject.BindEvent.AClick($(this).find('a[class="jAutoComboBox-address-autocomboboxitem"][key="' + keyname + '"]'), op);
        },
        Show: function (Animation, CallBack) {
            if (Animation == "hide") {
                $(this).find('div[class="jAutoComboBox-address-content"]').hide();
            }
            else if (Animation == "show") {
                $(this).find('div[class="jAutoComboBox-address-content"]').show();
            }
            else if (Animation == "slideDown") {
                $(this).find('div[class="jAutoComboBox-address-content"]').slideDown();
            }
            else if (Animation == "slideUp") {
                $(this).find('div[class="jAutoComboBox-address-content"]').slideUp();
            }
            else if (Animation == "fadeIn") {
                $(this).find('div[class="jAutoComboBox-address-content"]').fadeIn();
            }
            else if (Animation == "fadeOut") {
                $(this).find('div[class="jAutoComboBox-address-content"]').fadeOut();
            }
        },
        Methods: {
            GetVal: function (AutoComboBox, GetValCallBack) {
                if (AutoComboBox) {
                    var input = $(AutoComboBox).find("input[class='jAutoComboBox-address-input']");
                    input.val("");
                    var value = ""; //ID值
                    $(AutoComboBox).find('a[itemid][class*="selected"]').each(function (i, item) {
                        if (input.val()) {
                            input.val(input.val() + input.attr("splitchar") + $(item).text());
                            input.attr("itemid", input.attr("itemid") + input.attr("splitchar") + $(item).attr("itemid"))
                        }
                        else {
                            input.val($(item).text());
                            input.attr("itemid", $(item).attr("itemid"));
                        }
                    });
                    if (GetValCallBack)
                        GetValCallBack(input.val(), input.attr("itemid"));
                }
                else {
                    if (GetValCallBack)
                        GetValCallBack(false, false);
                }
            }
        }
    });

})(jQuery);